package com.edoovo.loginservice.application.config.auth;

import com.edoovo.loginservice.application.config.auth.CustomUserDetails;
import com.edoovo.loginservice.application.domain.Menu;
import com.edoovo.loginservice.application.domain.Role;
import com.edoovo.loginservice.application.domain.User;
import com.edoovo.loginservice.application.domain.UserStatus;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    @SuppressWarnings("all")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //todo 查询数据库
        //User user = userAccountService.userInfo(username);
        Menu menu = Menu.builder().id("1").name("User").auth(Lists.newArrayList("AUTH_USER")).build();
        Role role = Role.builder().id("1").name("admin").menus(Lists.newArrayList(menu)).build();
        User user = User.builder().id(1L).username("test").email("test@edoovo.com")
        		.password("$2a$10$2STYUVOsRjb1lr0ntmRfJOF2AxcSIIutWNVzgc9/EMI86UruQ2hwW").status("ACTIVE").role(role).build();
        
        HashSet<GrantedAuthority> set = Sets.newHashSet();

        //todo 组装用户权限
        List<Menu> menus = user.getRole().getMenus();
        List<String> authList = Lists.newArrayList();
        menus.forEach(m -> authList.addAll(m.getAuth()));
        authList.forEach(a -> set.add(new SimpleGrantedAuthority(a)));

        //todo 根据我的需求修改需要那些返回值
        return CustomUserDetails.builder()
                .username(user.getEmail())
                .password(user.getPassword())
                .userStatus(UserStatus.valueOf(user.getStatus()))
                .currentLoginDate(LocalDateTime.now())
                .id(user.getId().toString())
                .role(role.getName())
                .authorities(set)
                .build();
    }
    

    public void checkUserAccount(String username) {
    	//自定义查询User是否存在
    	// findUserByUsername
        if (false) {
        	throw new UsernameNotFoundException("Account was not found");
        }
    }

}